package com.itheima.controller;


import com.itheima.common.constant.MessageConstant;
import com.itheima.common.constant.RedisConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.UUID;

/**
 * 检查套餐管理
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    private static final Logger log = LoggerFactory.getLogger(SetmealController.class);
    @Autowired
    private SetmealService setmealService;

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 新增套餐 localhost:8080/setmeal/add?checkgroupIds=5,6,7,8,9
     *
     * @param setmeal       前端传递的json格式参数
     * @param checkgroupIds 由路径参数 query参数传递，须保持方法形参名与路径参数名一致
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds) {
        try {
    //          log.info("新增检查组:{},{}",setmeal,checkgroupIds);
            setmealService.add(setmeal, checkgroupIds);
   //          System.out.println("新增成功");

        } catch (Exception e) {
            //新增失败
            return new Result(false, MessageConstant.ADD_SETMEAL_FAIL);

        }
       //       System.out.println("这里执行了最后");
        String pictureName = setmeal.getImg();
        redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_DB_RESOURCES, pictureName);
        Result result = new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);


        return result;
    }

    /**
     * 根据id删除检查套餐
     * @param id 套餐id
     * @return
     */
    @RequestMapping("/delete")
    public Result delete(Integer id) {
        try {
            setmealService.deleteById(id);
        } catch (RuntimeException e) {
            return new Result(false, e.getMessage());
        } catch (Exception e) {
            return new Result(false, MessageConstant.DELETE_SETMEAL_FAIL);
        }
        return new Result(true, MessageConstant.DELETE_SETMEAL_SUCCESS);
    }

    @RequestMapping("/edit")
    public Result edit(@RequestBody Setmeal setmeal, Integer[] checkgroupIds) {
        try {
            setmealService.edit(setmeal, checkgroupIds);
        } catch (Exception e) {
            return new Result(false, MessageConstant.EDIT_SETMEAL_FAIL);
        }
        String pictureName = setmeal.getImg();
        redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_DB_RESOURCES, pictureName);
        return new Result(true, MessageConstant.EDIT_SETMEAL_SUCCESS);
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = setmealService.findPage(
                queryPageBean.getCurrentPage(),
                queryPageBean.getPageSize(),
                queryPageBean.getQueryString()
        );
        return pageResult;

    }

    //查询所有检查组
    @RequestMapping("/findAll")
    public Result findAll() {
      List<Setmeal> setmeals=  setmealService.findAll();
      if(setmeals!=null&&setmeals.size()>0){
          Result result = new Result(true,MessageConstant.QUERY_SETMEALLIST_SUCCESS);
          result.setData(setmeals);
          return result;
      }

         return new Result(false, MessageConstant.QUERY_SETMEALLIST_FAIL);
    }

    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try{
            Setmeal setmeal=  setmealService.findById(id);
            return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal);

        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        }

    }

    /**
     * 图片上传
     *
     * 1. 为了能够区分出来哪些图片是垃圾图片，在文件上传成功后将图片保存到了一个redis集合中
     * 2. 当套餐数据插入到数据库后我们又将图片名称保存到另一个redis集合中
     * 3. 通过计算这两个集合的差值就可以获得所有垃圾图片的名称。
     * @param imgFile  前端传递的图片文件名/位置
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile) {
        try {
            //获取原始文件名  C:\\Users\\Administrator.DESKTOP-5VUK56D\\Pictures\\4.jpg
            String fileName = imgFile.getOriginalFilename();
            //获取文件后缀
            int lastIndexOf = fileName.lastIndexOf(".");//从序号0开始
            String suffix = fileName.substring(lastIndexOf);//获取结果为 .jpg

            //使用UUID随机产生文件名称，防止同名文件覆盖
             fileName = UUID.randomUUID().toString()+suffix;
            log.info("图片文件名:{}",fileName);
            //使用阿里云oss上传图片
           String pictureUploadPath = aliOssUtil.upload(imgFile.getBytes(),fileName);
           redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
          String message = "图片上传后文件名:"+fileName+"OSS保存路径："+pictureUploadPath;//todo 后期删除打印语句
          //  图片回显   使用pictureUploadPath
            // 使用fileName 不能回显图片，但是省流量
            System.out.println(message);
            return new Result(true, MessageConstant.UPLOAD_SUCCESS,fileName);


        }catch (Exception e) {
            e.printStackTrace();
            return new Result(false, e.getMessage());
        }

    }
}